/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tsystems.school.server;

/**
 *
 * @author 123
 */
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
 
public class JServer implements Runnable{
 
    protected int          serverPort   = 8080;
    protected ServerSocket serverSocket = null;
    protected boolean      isStopped    = false;
    private List<Thread> workingThreads = null;
 
    public JServer(int port){
        this.serverPort = port;
        workingThreads = new LinkedList<Thread>();
        
    }

 
    @Override
    public void run(){
        openServerSocket();
        while(! isStopped()){
            Socket clientSocket = null;
            try {
                clientSocket = this.serverSocket.accept();
            } catch (IOException e) {
                if(isStopped()) {
                    System.out.println("Server Stopped.") ;
                    return;
                }
                throw new RuntimeException("Error accepting client connection", e);
            }
            Thread newWT = new Thread(
                new Worker(clientSocket)
            );
            newWT.start();
            workingThreads.add(newWT);
        }
        System.out.println("Server Stopped.") ;
    }
 
 
    private synchronized boolean isStopped() {
        return this.isStopped;
    }
 
    public synchronized void stop(){
        this.isStopped = true;
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            throw new RuntimeException("Error closing server", e);
        }
    }
 
    private void openServerSocket() {
        System.out.println("Opening server socket...");
     try {
            this.serverSocket = new ServerSocket(this.serverPort);
        } catch (IOException e) {
            throw new RuntimeException("Cannot open port " + this.serverPort, e);
        }
    }
 
}
